<template>
  <div>
    <div class="dashboard-container padding">
      <!-- 运单汇总 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="title-icon">{{ $t('dashboard.waybillSummary') }}</span>
        </div>
        <el-row v-if="waybillBtn" type="flex" class="waybill-nav">
          <el-col
            v-for="(item, index) in waybillBtn"
            :key="index"
            class="waybill-nav-item"
            @click.native="GoWaybill(item.status)"
          >
            <!-- <span>{{ $t(`waybill.${item.name}`) + `(${item.number})`}}</span> -->
            <router-link
              class="text-sm pan-btn "
              to="/icon/index"
              :class="{ 'text-red': item.name === 'problematic' }"
            >
              <div class="margin-bottom-sm">
                <svg-icon :name="item.icon" width="24" height="24" />
              </div>
              <div>
                {{ $t(`waybill.${item.name}`) + `(${item.number})` }}
              </div>
            </router-link>
          </el-col>
        </el-row>
      </el-card>

      <el-row :gutter="30" type="flex" class="flex-wrap">
        <el-col :md="12" :sm="24" class="margin-top">
          <!-- 财务中心 -->

          <div class>
            <div class="el-card__header bg-white shadow">
              <div slot="header" class="clearfix relative">
                <span class="title-icon">{{
                  $t('dashboard.financialCenter')
                }}</span>
                <!-- <el-button style="float: right; padding: 3px 0;" type="text">
                快速还款
              </el-button> -->
                <el-button
                  type="danger"
                  size="mini"
                  round
                  class="header-btn"
                  @click="openQuickRepay()"
                >快速还款</el-button>
              </div>
            </div>

            <el-row :gutter="20" class="margin-top">
              <el-col :span="12">
                <el-card class="box-card">
                  <div class="flex align-center justify-around">
                    <div>
                      <svg-icon
                        name="money-red"
                        style="fill: #04be02;"
                        width="64"
                        height="64"
                      />
                    </div>
                    <div>
                      <p class="financial-title">
                        当前余额
                      </p>
                      <p v-if="isCheckPrice" class="financial-title-money">
                        ¥ {{ accountBalance }}
                      </p>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="box-card">
                  <div class="flex align-center justify-around">
                    <div>
                      <svg-icon
                        name="money-red"
                        style="fill: #f56c6c;"
                        width="64"
                        height="64"
                      />
                    </div>
                    <div>
                      <p class="financial-title">
                        欠款金额
                      </p>
                      <p v-if="isCheckPrice" class="financial-title-money">
                        ¥{{ currentDebt }}
                      </p>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
          <!-- 新闻中心 -->
          <!-- <el-card class="box-card margin-top">
          <div slot="header" class="clearfix">
            <span class="title-icon">{{ $t('dashboard.newsCenter') }}</span>
          </div>
          <el-timeline class="padding-top-xl">
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="activity.cdate"
            >
              {{ activity.description }}
            </el-timeline-item>
          </el-timeline>
        </el-card> -->
        </el-col>
        <!-- 运单列表 -->
        <el-col :md="12" :sm="24" class="margin-top">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span class="title-icon">{{ $t('dashboard.waybillList') }}</span>
            </div>
            <el-table
              :data="tableData"
              style="width: 100%;"
              class="padding-lr-sm"
            >
              <el-table-column type="index" width="60" prop="id" label="序号" />
              <el-table-column prop="waybillNo" label="运单号" />
              <el-table-column prop="referenceNo" label="参考号" />
              <el-table-column prop="statusName" label="状态" />

              <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                  <div class="flex align-center">
                    <el-tooltip
                      class="item margin-left-xs"
                      effect="dark"
                      content="起运港账单状态,灰色未出账单;绿色已出账单"
                      placement="top"
                    >
                      <img
                        v-if="scope.row.billStatus === 1"
                        src="@/assets/images/yes_bill_status.png"
                      >
                      <img
                        v-if="scope.row.billStatus != 1"
                        src="@/assets/images/no_bill_status.png"
                      >
                    </el-tooltip>
                    <el-tooltip
                      v-if="scope.row.status === 10"
                      class="item margin-left-xs"
                      effect="dark"
                      content="编辑"
                      placement="top"
                    >
                      <i
                        class="el-icon-edit-outline operation-icon"
                        @click="colEdit(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip
                      v-if="scope.row.status === 10"
                      class="item margin-left-xs"
                      effect="dark"
                      content="删除"
                      placement="top"
                    >
                      <i
                        class="el-icon-close operation-icon"
                        @click="colDel(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip
                      class="item margin-left-xs"
                      effect="dark"
                      content="查看订单详情"
                      placement="top"
                    >
                      <i
                        class="el-icon-zoom-in operation-icon"
                        @click="colCheckDetails(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip
                      class="item margin-left-xs"
                      effect="dark"
                      content="复制"
                      placement="top"
                    >
                      <i
                        class="el-icon-document-copy operation-icon pointer"
                        @click="colEdit(scope.row, 'copy')"
                      />
                    </el-tooltip>
                    <el-tooltip
                      class="item margin-left-xs"
                      effect="dark"
                      content="下载已上传装箱单"
                      placement="top"
                    >
                      <i
                        class="el-icon-download operation-icon"
                        @click="colDownload(scope.row)"
                      />
                    </el-tooltip>
                    <el-popover
                      class="item margin-left-xs"
                      placement="top"
                      trigger="hover"
                    >
                      <div>
                        <el-divider content-position="left">
                          请选择预览打印的方式(A4纸每页打印6个标签)
                        </el-divider>
                        <el-button
                          size="mini"
                          type="success"
                          @click="colPrinter({ row: scope.row, index: 0 })"
                        >
                          10*10
                        </el-button>
                        <el-button
                          size="mini"
                          type="success"
                          @click="colPrinter({ row: scope.row, index: 1 })"
                        >
                          10*10(PDF)
                        </el-button>
                        <el-button
                          size="mini"
                          type="success"
                          @click="colPrinter({ row: scope.row, index: 2 })"
                        >
                          10*8(PDF)
                        </el-button>
                        <el-button
                          size="mini"
                          type="success"
                          @click="colPrinter({ row: scope.row, index: 3 })"
                        >
                          A4(PDF)
                        </el-button>
                      </div>

                      <div slot="reference">
                        <i class="el-icon-printer operation-icon" />
                      </div>
                    </el-popover>
                    <el-tooltip
                      v-if="scope.row.status === 20"
                      class="item margin-left-xs"
                      effect="dark"
                      content="打回待确认"
                      placement="top"
                    >
                      <svg-icon
                        class="operation-icon pointer"
                        name="return"
                        @click="colReturn(scope.row)"
                      />
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-card class="box-card margin-top">
      <div slot="header" class="clearfix">
        <span class="title-icon">合作伙伴</span>
      </div>
      <el-row>
        <el-col :md="4" :lg="4">
          <div class="flex">
            <div class="margin-right ">
              <a href="http://www.worldfirst.com.cn" target="_blank">
                <img
                  src="../../assets/images/wlh.jpg"
                  alt="FBA头程物流合作伙伴-world First"
                  title="FBA头程物流合作伙伴-world First"
                  width="95"
                >
              </a>
            </div>
            <div>
              <div class="text-bold text-lg margin-bottom-xs">万里汇</div>
              <span
                style="color:#666"
              >跨境收款费率0至0.3%，蚂蚁集团旗下17年跨境支付品牌，安全放心。
              </span>
            </div>
          </div>
        </el-col>
        <el-col :md="4" :lg="4">
          <div class="text-bold text-lg margin-bottom-sm margin-left">
            <a
              href="https://csp.ces-group.cn/#/register"
              target="_blank"
            >金融服务
            </a>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  initListPage,
  listPage,
  deleteWaybillById,
  replyWaybill,
  createPdfLabel10x10,
  createPdfLabel10x8,
  exportLiquidationPacking,
  createPdfLabelA4,
  printWaybillLabel
} from '@/api/waybill'
import { compileStr } from '@/utils'
import { officewebnews } from '@/api/public'

import { getInfo } from '@/api/user'
import { getLodop } from '@/utils/LodopFuncs'
import globalData from '@/utils/config'
export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters(['name', 'publicData', 'isCheckPrice', 'sidebar'])
  },
  data() {
    return {
      showInfo: false,
      activities: [],
      tableData: [],

      waybillBtn: [
        {
          name: 'waybillAll',
          number: 0,
          status: 0,
          icon: 'all-line'
        },
        {
          name: 'waitForConfirm',
          number: 0,
          status: 10,
          icon: 'confirm-line'
        },
        {
          name: 'waitForDealSend',
          number: 0,
          status: 20,
          icon: 'send-out'
        },
        {
          name: 'waitForOutStock',
          number: 0,
          status: 40,
          icon: 'out-of-stock'
        },
        // {
        //   name: 'waitForToThePort',
        //   number: 0,
        //   status:90,
        //   icon: 'landing'
        // },
        {
          name: 'waitForSign',
          number: 0,
          status: 140,
          icon: 'Logistics'
        },
        {
          name: 'alrSeadySigned',
          number: 0,
          status: 999,
          icon: 'order-success'
        },
        {
          name: 'problematic',
          number: 0,
          status: 900,
          icon: 'caveat-line'
        },
        {
          name: 'alrSeadyReturned',
          number: 0,
          status: -20,
          icon: 'order-err'
        }
      ],
      currentDebt: 0, // 当前欠款
      accountBalance: 0 // 当前余额
    }
  },
  mounted() {
    this.init()
    // this.getCustomerSalesmanService()
  },
  methods: {
    async init() {
      const dataCont = await initListPage({})
      for (var key in dataCont) {
        this.waybillBtn.forEach(data => {
          if (data.status == key) {
            data.number = dataCont[key]
          }
        })
      }

      const user = await getInfo({})
      console.log('user', user)
      if (user) {
        if (user.currentDebt > 0) {
          this.accountBalance = 0
          this.currentDebt = user.currentDebt
          console.log('this.accountBalance 0 :>> ', this.accountBalance)
          console.log('0 :>> ', this.currentDebt)
        } else if (user.currentDebt < 0) {
          this.accountBalance = Math.abs(user.currentDebt)
          this.currentDebt = 0
          console.log('this.accountBalance :>> ', this.accountBalance)
          console.log('0 :>> ', this.currentDebt)
        }
      }

      this.queryList()

      const dataNews = await officewebnews({})
      // console.log("officewebnews",dataNews);
      this.activities = dataNews
    },

    async queryList() {
      const list = await listPage({})
      // console.log("list",list);
      this.tableData = list.datas
      // console.log("tableData",this.tableData);
      const statusMap = this.publicData.waybillStatusMap
      // console.log("statusMap",statusMap)
      if (this.tableData !== null) {
        this.tableData.forEach(data => {
          for (var key in statusMap) {
            if (data.status == key) {
              data.statusName = this.$t('waybill.' + statusMap[key])
              // console.log("tableData",this.$t("waybill."+statusMap[key]))
            }
          }
        })
      }
    },
    GoWaybill(s) {
      this.$router.push({ name: 'WaybillList', params: { status: s }})
    },

    colEdit(row, type) {
      const a = 'ZX,AIR'
      const s = 'FCL,LCL'
      // const e = '99'

      let name = ''
      let tab = ''
      if (a.indexOf(row.shippingWay) > -1 && row.waybillType !== 'C') {
        // 空运下单
        name = 'orderToAirFreight'
      } else if (s.indexOf(row.shippingWay) > -1 && row.waybillType !== 'C') {
        // 海运下单
        name = 'orderToSeaFreight'
      } else if (row.waybillType === 'C') {
        // 港到港下单
        name = 'addAirSeag2gwaybill'
      } else {
        // 快递下单
        name = 'orderToExpressDelivery'
      }
      if (row.isFba) {
        // 快捷下单
        tab = 'quickOrder'
      } else {
        // 标准下单
        tab = 'standardOrder'
      }

      this.$router.push({
        path: `/waybillManagement/${name}`,
        query: {
          tab: tab,
          id: compileStr(row.id.toString()),
          isCopy: type ? 1 : 0
        }
      })
    },

    colDel(id) {
      this.$confirm('确定要删除吗？')
        .then(_ => {
          this.delteRow(id)
        })
        .catch(_ => {})
    },
    async delteRow(row) {
      this.$store.dispatch('app/toggleDialog', true)
      const { code, message } = await deleteWaybillById({ id: row.id })

      if (code === 200) {
        this.$message({
          message: '删除成功!',
          type: 'success'
        })
        this.queryList()
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async colDownload(row) {
      this.$store.dispatch('app/toggleDialog', true)

      const data = await exportLiquidationPacking({ id: row.id })

      if (data.path) {
        window.open(globalData.fileUrl + data.path)
      } else {
        this.$message.error(data.errorMesage || '下载失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async colReturn(row) {
      const { code, message } = await replyWaybill({ id: row.id })

      if (code === 200) {
        this.$message({
          message: '运单已打回待确认!',
          type: 'success'
        })
        this.queryList()
      } else {
        this.$message.error(message)
      }
    },
    async colPrinter({ row, index, batch }) {
      let list = []
      if (batch) {
        for (const i of this.selection) {
          list.push(i.id)
        }
      } else {
        list = [row.id]
      }
      if (index !== 0) {
        this.$store.dispatch('app/toggleDialog', true)
      }
      let data
      switch (index) {
        case 0:
          data = await printWaybillLabel({
            waybillIds: list
          })
          if (data.code === 200) {
            if (data.data.length > 0) {
              // this.printList = data.data
              this.getLodopFn(data.data)
            } else {
              this.$message.error('暂无数据')
            }
          } else {
            this.$message.error(data.message || '请求失败')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 1:
          data = await createPdfLabel10x10({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 2:
          data = await createPdfLabel10x8({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 3:
          data = await createPdfLabelA4({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
      }

      // console.log('data :>> ', data)
    },
    getLodopFn(htmls, printName) {
      const LODOP = getLodop()

      if (!htmls) {
        return
      }
      if (!LODOP) {
        return
      }
      LODOP.PRINT_INIT('打印订单信息')
      LODOP.SET_PRINT_PAGESIZE(1, '100mm', '100mm', 'CreateCustomPage')
      for (var j = 0; j < htmls.length; j++) {
        var html = htmls[j]
        LODOP.ADD_PRINT_HTM(0, 0, '100mm', '98mm', html)
        var body = document.querySelector('body')
        const div = document.createElement('div')
        div.setAttribute('id', 'templateContentHtml')
        div.style.display = 'none'
        div.innerHTML = html
        body.appendChild(div)
        var barCodes = document.getElementsByName('barcode')
        for (var i = 0; i < barCodes.length; i++) {
          var barCode = barCodes[i]
          var value = barCode.getAttribute('value')
          var values
          if (value.indexOf('|') >= 0) {
            values = barCode.getAttribute('value').split('|')
          } else {
            values = barCode.getAttribute('value').split('-')
          }
          LODOP.ADD_PRINT_BARCODE(
            values[0],
            values[1],
            values[2],
            values[3],
            values[4],
            values[5]
          )
          LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 1)
          if (values[6] == 1 || typeof values[6] === 'undefined') {
            LODOP.SET_PRINT_STYLEA(0, 'AlignJustify', 2)
          } else {
            LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
          }
        }
        var templateContentHtml = document.querySelector('templateContentHtml')
        this.removeDom(templateContentHtml)
        LODOP.NewPage() // 分页
      }
      if (printName) {
        LODOP.SET_PRINTER_INDEX(printName)
      } else {
        LODOP.PREVIEW()
      }
    },
    // 移除节点
    removeDom(model) {
      var self = this
      if (self.$parent.model) {
        self.$parent.model.children.forEach((item, index) => {
          if (item.name == model.name) {
            self.$parent.model.children.splice(index, 1)
          }
        })
      }
    },

    colCheckDetails(row) {
      const routeUrl = this.$router.resolve({
        name: 'WaybillDetails',
        params: { id: compileStr(row.id.toString()) }
      })

      window.open(routeUrl.href, '_blank')
    },
    // colCheckDetails(row) {
    //   console.log('row :>> ', row)
    //   this.$router.push({
    //     name: 'WaybillDetails',
    //     params: { waybillId: row.id }
    //   })
    // },
    openQuickRepay() {
      this.$router.push({
        name: 'QuickRepayment',
        params: {
          currentDebt: this.currentDebt
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-col {
  border-radius: 4px;
}

.pan-btn {
  font-size: 12px;
  // color: #fff;
  color: #3f4652;
  width: 100%;
  padding: 14px 0;
  border-radius: 8px;
  border: none;
  outline: none;
  transition: 600ms ease all;
  position: relative;
  display: inline-block;
  text-align: center;
  cursor: pointer;
  &:hover {
    color: #30b08f;
    // background: #ccc;

    &:before,
    &:after {
      background: #30b08f;
      width: 100%;
      transition: 600ms ease all;
    }
  }

  &:before,
  &:after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    height: 2px;
    width: 0;
    transition: 400ms ease all;
  }

  &::after {
    right: inherit;
    top: inherit;
    left: 0;
    bottom: 0;
  }
}

.financial-title {
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
  text-align: center;
}

.financial-title-money {
  color: #666;
  font-size: 20px;
  text-align: center;
}

.shadow {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-btn {
  position: absolute;
  right: 4px;
  top: -40%;
}
.operation-icon {
  font-size: large;
}
</style>
